﻿/*
   @Description:agency中委托备案模块js
   @Author:ZB,YPL
   @Date:2014-04-16 
 */

var OnlyTrust = {};
var PopupWindowRecord = {};

//查看合同书事件
OnlyTrust.appendShowContractBookClickEvent = function (selector) {
    $(selector).next().next().show();
    $(selector).parent().siblings().find("ul").hide();
};

//隐藏合同书事件
OnlyTrust.appendHideContractBookClickEvent = function (selector) {
    $(selector).parent().parent().hide();
};

//删除合同书
OnlyTrust.delContractBookClickEvent = function (selector) {
    $(selector).parent().remove();
};

//检测委托类型数据
PopupWindowRecord.checkTypeDataValue = true;
PopupWindowRecord.checkTypeData = function () {
    var currentType = $('#divOnlyTrustType input[name=OnlyTrustType]:checked');
       if ($(currentType).val() == '1' || $(currentType).val() == '2' || $(currentType).val() == '3' || $(currentType).val() == undefined) {
        if ($(currentType).val() == undefined && !$('#btnPopupTrustsTime1').val() && !$('#btnRegisterPerson').val()) {
            PopupWindowRecord.checkTypeDataValue = true;
            return true;
        }
        if ($(currentType).val() == undefined) {
            $.OKDialogAgency("类型不能为空！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if (!$('#btnPopupTrustsTime1').val()) {
            $.OKDialogAgency("签署日期不能为空！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if ($('#uploadContractBookDivTrust').find('div[attachmentName]').length < 3) {
            $.OKDialogAgency("至少上传3个附件！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if ($('#uploadContractBookDivTrust').find('div[attachmentName]').length > 50) {
            $.OKDialogAgency("至多上传50个附件！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if (!$('#btnTrustdate').val()) {
            $.OKDialogAgency("委托开始日期不能为空！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if (!$('#btnExpiredate').val()) {
            $.OKDialogAgency("委托结束日期不能为空！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        var startTime = $("#btnTrustdate").val();
        var start = new Date(startTime.replace("-", "/").replace("-", "/"));
        var endTime = $("#btnExpiredate").val();
        var end = new Date(endTime.replace("-", "/").replace("-", "/"));
        if (end < start) {
            $.OKDialogAgency("委托结束日期大于委托开始日期！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if (!$('#btnRegisterPerson').val()) {
            $.OKDialogAgency("签署人不能为空！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        if (!$('#hidUserId').val()) {
            $.OKDialogAgency("签署人请从下拉框选取！");
            PopupWindowRecord.checkTypeDataValue = false;
            return false;
        }
        PopupWindowRecord.checkTypeDataValue = true;
    }

};

//上传合同书成功后调用方法
function uploadSuccessContractBookTrust(file, serverData) {
    var imgServicePath = $("#ImgServicePath").val();
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("Complete.");
        progress.toggleCancel(false);
        var innerHtml = '<div class="rel" AttachmentName="' + file.name + '" AttachmentPath="' + serverData + '"><a style="display:inline-block;width:auto !important;max-width:240px;width:240px;overflow:hidden;display:inline-block;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap;" title=' + file.name + ' onclick="photoView(\'' + imgServicePath + serverData + '\')" >'
            + file.name + '</a><i onclick="OnlyTrust.delContractBookClickEvent(this);" title="删除" class="red ml4 vm fb cp">×</i><ul style="display:none;overflow:visible;position:absolute;z-index:9999;"><li><img style="width:150px;height:200px;" src="' + other.getFullPhotoPath($("#hidImageDownloadUrl").val(), serverData) + '" /></li><li><i title="关闭" class="cp" style="display:inline-block;width:20px;height:20px;line-height:20px;color:#FFF;text-align:center;background:#000;opacity:.4;filter:alpha(opacity=40);position:absolute;right:0;top:0;" onclick="OnlyTrust.appendHideContractBookClickEvent(this);">×</i></li></ul></div>';
        $("#uploadContractBookDivTrust").append(innerHtml);

    } catch (ex) {
        this.debug(ex);
    }
}

PopupWindowRecord.makeUploadBtn = function () {
    //上传合同书
    var settings = {
        flash_url: "/Scripts/PageHelper/swfupload1.swf",
        upload_url: $("#uploadPath").val(),
        post_params: {},
        file_size_limit: "4 MB",
        file_types: "*.jpg;*.png",
        file_types_description: "JPG Images",
        file_upload_limit: 20,
        file_queue_limit: 20,
        custom_settings: {
            progressTarget: "fsUploadProgress"
        },
        debug: false,
        // Button settings
        button_image_url: "",
        button_width: "63",
        button_height: "20",
        button_placeholder_id: "uploadSpanContractBookTrust",
        button_cursor: SWFUpload.CURSOR.HAND,
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_text: '<span class="btntext">添加附件</span>',
        button_text_style: ".btntext{color:#1f73f0;}",
        //button_text_left_padding: 12,
        //button_text_top_padding: 3,

        // The event handler functions are defined in handlers.js
        file_queued_handler: fileQueued,
        file_queue_error_handler: fileQueueErrorTrust,
        file_dialog_complete_handler: fileDialogComplete,
        upload_start_handler: uploadStart,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccessContractBookTrust,
        upload_complete_handler: uploadComplete,
        queue_complete_handler: queueComplete,	// Queue plugin event

    };
    //上传组件模拟文字链接
    $("#spanSwfuploadTrust").hover(function () {
        $(this).find($("#uploadSpanContractBookTrust")).css("opacity", "1");
        $(this).find($(".abs")).hide();
    }, function () {
        $(this).find($("#uploadSpanContractBookTrust")).css("opacity", "0");
        $(this).find($(".abs")).show();
    });
    var swfu = new SWFUpload(settings);
};

//委托备案图片大小验证
function fileQueueErrorTrust(file, errorCode, message) {
    try {

        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);

        switch (errorCode) {
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                progress.setStatus("上传文件必须小于4M");
                this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                progress.setStatus("Cannot upload Zero Byte files.");
                this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                progress.setStatus("Invalid File Type.");
                this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            default:
                if (file !== null) {
                    progress.setStatus("图片大小不符合规则！");
                }
                this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}



PopupWindowRecord.btnAddEntrustRecord = function (element) {
    PopupWindowRecord.checkTypeData();
    if (!PopupWindowRecord.checkTypeDataValue) {
        return false;
    }
    var DialogContent = "委托备案";
    var OnlyTrustType = $('#divOnlyTrustType input[name=OnlyTrustType]:checked').val();
    switch (OnlyTrustType) {
        case "1":
            DialogContent = "售房委托";
            break;
        case "2":
            DialogContent = "租房委托";
            break;
        case "3":
            DialogContent = "租售委托";
        default:
    }
    $.OKCancelDialogAgency('<div class="tc">您确定要提交保存' + DialogContent + '吗？</div>', '保存' + DialogContent + '', true, function () {
        var attachmentNames = [], attachmentPaths = [], contactKeyIds = [], contactDeptKeyIds = [], contactsName = [];
        $("#uploadContractBookDivTrust").find("div").each(function (index, e) {
            attachmentNames[index] = ($(this).attr("AttachmentName"));
            attachmentPaths[index] = ($(this).attr("AttachmentPath"));
        });

        if ($(element).attr('onlytype') == 'edit') {
            var reqData = {
                "type": "edit",
                "keyId": $('#hidOnlyKeyId').val(),
                "OnlyTrustType": $('#divOnlyTrustType input[name=OnlyTrustType]:checked').val(),
                "PropertyKeyId": $("#hidPropertyChiefDepartmentKeyId").attr("keyid"),
                "PersonKeyId": $('#hidUserId').val(),
                "PersonName": $("#btnRegisterPerson").val(),
                "DepartmentKeyId": $("#hidDepartmentKeyId").val(),
                "SignDate": $("#btnPopupTrustsTime1").val(),
                "AttachmentNames": attachmentNames.join(","),
                "AttachmentPaths": attachmentPaths.join(","),
                "EffectiveDate": $("#btnTrustdate").val(),
                "ExpirationDate": $("#btnExpiredate").val(),

            };
            if ($('#divOnlyTrustType input[name=OnlyTrustType]:checked').val() == undefined && $("#btnRegisterPerson").val() == "" && $("#btnPopupTrustsTime1").val() == "") {
                $.AjaxAgency('/property/property-trust-record-remove-ajax', reqData, function (data) {
                    if (data == 'ok') {
                        art.dialog.get('turnEntrust').close();
                        $.OKDialogAgency('<div class="tc">删除成功!</div>', '提示', function () {
                            window.location.reload();
                        });
                    } else {
                        $.OKDialogAgency('<div class="tc">' + data + '</div>');
                    }
                });
            }
            else {
                $.AjaxAgency('/property/property-trust-record-modify-ajax', reqData, function (data) {
                    if (data == 'ok') {
                        art.dialog.get('turnEntrust').close();
                        $.OKDialogAgency('<div class="tc">编辑成功!</div>', '提示', function () {
                            window.location.reload();
                        });
                    } else {
                        $.OKDialogAgency('<div class="tc">' + data + '</div>');
                    }
                });
            }
        } else {
            var reqData = {
                "OnlyTrustType": $('#divOnlyTrustType input[name=OnlyTrustType]:checked').val(),
                "PropertyKeyId": $("#hidPropertyChiefDepartmentKeyId").attr("keyid"),
                "PersonKeyId": $('#hidUserId').val(),
                "PersonName": $("#btnRegisterPerson").val(),
                "DepartmentKeyId": $("#hidDepartmentKeyId").val(),
                "SignDate": $("#btnPopupTrustsTime1").val(),
                "AttachmentNames": attachmentNames.join(","),
                "AttachmentPaths": attachmentPaths.join(","),
                "EffectiveDate": $("#btnTrustdate").val(),
                "ExpirationDate": $("#btnExpiredate").val(),
            };
            if ($('#divOnlyTrustType input[name=OnlyTrustType]:checked').val() == undefined && !$('#btnPopupTrustsTime1').val() && !$('#btnRegisterPerson').val()) {
                $.OKDialogAgency('<div class="tc">' + '请填写委托备案内容' + '</div>');
                return;
            }
            $.AjaxAgency("/property/property-trust-record-add-ajax", reqData, function (data) {
                if (data.length == 36) {
                    art.dialog.get('turnEntrust').close();
                    $.OKDialogAgency('<div class="tc">保存成功!</div>', '提示', function () {
                        window.location.reload();
                    });
                } else {
                    $.OKDialogAgency('<div class="tc">' + data + '</div>');
                }
            });
        }
    });
};